// 在文件顶部添加api模块导入
const api = {
    get: async (url) => {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            throw error;
        }
    }
};
document.addEventListener('DOMContentLoaded', async function () {
    try {
        // 修正路径：使用相对路径 /knowledge.json
        const knowledgeData = await api.get('/data/knowledge.json');
        renderKnowledgeCards(knowledgeData);
        initKnowledgeCarousel();
    } catch (error) {
        console.error('Error loading knowledge data:', error);
    }

    if (window.location.pathname.endsWith('details.html')) {
        loadKnowledgeDetails();
    }
});

// 新增：加载知识详情内容
async function loadKnowledgeDetails() {
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const id = urlParams.get('id');
        
        if (!id) throw new Error('Missing knowledge ID in URL');
        
        // 修正路径：使用相对路径 /knowledge.json
        const knowledgeData = await api.get('/data/knowledge.json'); // 修改点
        const item = knowledgeData.find(i => i.id.toString() === id);
        
        if (!item) throw new Error(`Knowledge item with ID ${id} not found`);
        
        // 填充页面内容
        document.getElementById('knowledgeTitle').textContent = item.title;
        document.getElementById('knowledgeImage').src = item.image;
        
        const contentContainer = document.getElementById('knowledgeContent');
        contentContainer.innerHTML = `
            <p class="text-gray-700 text-lg mb-6">${item.description}</p>
            <div class="space-y-6">
                ${item.content.map(section => `
                    <div>
                        <h4 class="font-semibold text-xl text-gray-800 mb-2">${section.head}</h4>
                        <p class="text-gray-600 leading-relaxed">${section.body}</p>
                    </div>
                `).join('')}
            </div>
        `;
    } catch (error) {
        console.error('Error loading knowledge details:', error);
        document.getElementById('knowledgeContent').innerHTML = `
            <div class="text-red-500 p-4 bg-red-50 rounded-md">
                <i class="fas fa-exclamation-circle mr-2"></i>
                知识内容加载失败：${error.message}
            </div>
        `;
    }
}


// 动态生成知识卡片
function renderKnowledgeCards(knowledgeCards) {
    const container = document.getElementById('knowledgeCardsContainer');

    if (!container) return;
    
    container.innerHTML = knowledgeCards.map(card => `
        <a href="${card.link}" class="border border-gray-200 rounded-lg overflow-hidden shadow-md hover:shadow-lg transition duration-300 block">
            <img src="${card.image}" alt="${card.title}" class="w-full h-48 object-cover">
            <div class="p-4">
                <h3 class="text-xl font-semibold text-gray-800 mb-2">${card.title}</h3>
                <p class="text-gray-700 text-sm mb-3">${card.description}</p>
                <span class="text-blue-600 hover:underline text-sm">
                    <i class="fas fa-arrow-right mr-1"></i> 了解更多
                </span>
            </div>
        </a>
    `).join('');
}

// 初始化轮播功能
async function initKnowledgeCarousel() {
    try {
        const knowledgeData = await api.get('/data/knowledge.json');
        const carouselTrack = document.querySelector('#knowledgeCarousel .carousel-track');
        
        // 创建轮播项
        carouselTrack.innerHTML = knowledgeData.map(item => `
            <div class="carousel-item w-full flex-shrink-0 flex flex-col">
                <img src="${item.image}" alt="${item.title}" class="w-full h-48 object-cover rounded-md mb-3">
                <h3 class="text-xl font-bold text-gray-800 mb-2">${item.title}</h3>
                <p class="text-gray-700 mb-4">${item.description}</p>
                <div class="space-y-2">
                    ${item.content.map(contentItem => `
                        <div>
                            <h4 class="font-semibold text-gray-700">${contentItem.head}</h4>
                            <p class="text-gray-600 text-sm">${contentItem.body}</p>
                        </div>
                    `).join('')}
                </div>
            </div>
        `).join('');

        // 初始化轮播逻辑
        let currentIndex = 0;
        const items = document.querySelectorAll('.carousel-item');
        const totalItems = items.length;

        function showSlide(index) {
            if (index >= totalItems) currentIndex = 0;
            else if (index < 0) currentIndex = totalItems - 1;
            else currentIndex = index;
            
            carouselTrack.style.transform = `translateX(-${currentIndex * 100}%)`;
        }

        // 自动播放
        setInterval(() => {
            showSlide(currentIndex + 1);
        }, 5000);

        // 按钮点击事件
        document.querySelector('.carousel-btn.prev')?.addEventListener('click', () => {
            showSlide(currentIndex - 1);
        });

        document.querySelector('.carousel-btn.next')?.addEventListener('click', () => {
            showSlide(currentIndex + 1);
        });

    } catch (error) {
        console.error('Error initializing carousel:', error);
    }
}

// 初始化AI问答功能
document.getElementById('askAIBtn')?.addEventListener('click', sendQuestion);
document.getElementById('aiQuestionInput')?.addEventListener('keypress', function(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendQuestion();
    }
});

// 修改sendQuestion函数以适配新API接口
async function sendQuestion() {
    const input = document.getElementById('aiQuestionInput');
    const question = input.value.trim();
    if (!question) return;

    // 显示用户消息
    addMessage(question, 'user');
    input.value = '';

    const container = document.getElementById('chatContainer');
    if (!container) return;

    // 创建加载动画元素（仅保留文字闪烁）
    const loadingMsg = document.createElement('div');
    loadingMsg.className = 'flex justify-start items-start space-x-2';
    loadingMsg.innerHTML = `
        <i class="fas fa-robot text-purple-500 mr-2"></i>
        <div class="p-3 rounded-lg bg-gray-200 text-gray-800 rounded-bl-none">
            <span class="blinking-text">加载中...</span>
        </div>
    `;
    // 添加闪烁动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0; }
        }
        .blinking-text {
            animation: blink 1.5s infinite;
        }
    `;
    document.head.appendChild(style);
    
    container.appendChild(loadingMsg);
    container.scrollTop = container.scrollHeight;

    try {
        // 从服务器加载加密的API密钥
        const response = await fetch('/data/apikey.txt');  // 假设该文件为加密后的密钥
        if (!response.ok) throw new Error('加载API密钥失败');

        // 解密API密钥（假设使用Base64解码）
        let stringPromise = await response.text();
        const trimmedKey = stringPromise.trim();
        const aiResponse = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${trimmedKey}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                model: "Qwen/QwQ-32B",
                // 增加系统提示词，限制回答范围
                messages: [
                    { 
                        role: "system", 
                        content: "你是专业的劳动法律助手，专注于劳动合同、薪资福利、劳动保障等劳动领域知识，对非劳动相关问题请礼貌说明无法回答。回答需符合中国法律法规，保持专业性和准确性。"
                    },
                    { 
                        role: "user", 
                        content: `请专业解答以下劳动相关问题：${question}` 
                    }
                ],
                temperature: 0.7,
                max_tokens: 1024
            })
        });

        if (!aiResponse.ok) {
            throw new Error(`HTTP error! status: ${aiResponse.status}`);
        }

        const data = await aiResponse.json();
        const answer = data.choices?.[0]?.message?.content || '未获取到有效回答';

        // 显示对话内容
        addMessage(answer, 'assistant');
    } catch (error) {
        console.error('AI请求失败:', error);
        addMessage('抱歉，获取回答时发生错误', 'assistant');
    } finally {
        // 移除加载动画
        loadingMsg.remove();
        // 移除动态添加的样式
        document.head.removeChild(style);
    }
}

// 添加消息到聊天窗口
function addMessage(content, type) {
    const container = document.getElementById('chatContainer');
    if (!container) return;
    
    // 创建消息元素
    const msgDiv = document.createElement('div');
    msgDiv.className = `flex ${type === 'user' ? 'justify-end' : 'justify-start'} items-start space-x-2`;
    
    const icon = document.createElement('div');
    icon.className = "flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center";
    icon.innerHTML = type === 'user' 
        ? '<i class="fas fa-user text-blue-500"></i>' 
        : '<i class="fas fa-robot text-purple-500"></i>';
    
    const contentDiv = document.createElement('div');
    contentDiv.className = `p-3 rounded-lg max-w-md ${
        type === 'user' 
            ? 'bg-purple-600 text-white rounded-br-none' 
            : 'bg-gray-200 text-gray-800 rounded-bl-none'
    }`;
    contentDiv.textContent = content;
    
    // 组装消息元素
    if (type === 'user') {
        msgDiv.appendChild(contentDiv);
        msgDiv.appendChild(icon);
    } else {
        msgDiv.appendChild(icon);
        msgDiv.appendChild(contentDiv);
    }
    
    // 添加到容器并自动滚动
    container.appendChild(msgDiv);
    container.scrollTop = container.scrollHeight;

}
